package net.bplaced.streetfighter.fragment;

import java.util.ArrayList;
import java.util.List;

import net.bplaced.streetfighter.R;
import net.bplaced.streetfighter.adapter.TeamAdapter;
import net.bplaced.streetfighter.lib.async.task.TeamLoaderTask;
import net.bplaced.streetfighter.lib.model.Team;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class TableFragment
        extends Fragment {

    private LinearLayout view = null;
    private TeamAdapter teamAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        this.view = (LinearLayout) inflater.inflate(R.layout.view_table, container, false);

        this.prepareView();
        this.startFetchTable();

        return this.view;
    }

    private void prepareView() {

        final ListView table = (ListView) this.view.findViewById(R.id.table_list);

        final List<Team> teams = new ArrayList<Team>();
        teams.add(new Team());

        this.teamAdapter = new TeamAdapter(this.getActivity(), teams);

        table.setAdapter(this.teamAdapter);
    }

    private void startFetchTable() {

        final TeamLoaderTask task =
                new TeamLoaderTask(this.getActivity(), this.getResources().getString(R.string.table_progress_message),
                        this.onFinishedLoading);
        task.execute("");
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<Team[]>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<Team[]>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<Team[]> result) {

                    if (result != null) {
                        if (result.getContent() != null) {

                            TableFragment.this.teamAdapter.addAll(result.getContent());
                        } else {

                            Toast.makeText(TableFragment.this.getActivity(), result.getErrorMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                };
            };
}